package com.emmmya.ocs.filter;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
 
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
 
 
/**
 * http host头攻击漏洞处理过滤器，
 * 需要在配置文件添加allowed.servernames可访问host白名单，
 * 多个host用逗号隔开，本地开发使用127.0.0.1,localhost
 */
@Component
public class HostFilter implements Filter{
	  /**
	   * 自定义实现host白名单添加
	   */
	  @Value("${sys.servernames}")
	  private String ALLOWED_SERVERNAMES;
	 
	  @Override
	  public void init(FilterConfig filterConfig) throws ServletException {
//	    System.out.println("Filter初始化中");
	  }
	 
	  /**
	   * host拦截
	   */
	  @Override
	  public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
	      FilterChain filterChain) throws IOException, ServletException {
	    HttpServletRequest request = (HttpServletRequest) servletRequest;
	    HttpServletResponse response = (HttpServletResponse) servletResponse;
//	    String host = request.getHeader("host");
	    String serverName = request.getServerName();
	    //System.out.println("serverName-debug:" + serverName);
	    if (!isEmpty(serverName)) {
	      if (checkBlankList(serverName)) {
	        filterChain.doFilter(servletRequest, servletResponse);
	      } else {
	        //System.out.println("[serverName deny access tips]->" + serverName);
//	        response.getWriter().print("host deny");
	        response.setStatus(403);
	        response.flushBuffer();
	      }
	    } else {
	      filterChain.doFilter(servletRequest, servletResponse);
	    }
	 
	  }
	 
	  @Override
	  public void destroy() {
//	    System.out.println("Filter销毁");
	  }
	 
	  /**
	   * 校验当前host是否在白名单中
	   */
	  private boolean checkBlankList(String serverName) {
	    String[] allowdServerName = ALLOWED_SERVERNAMES.split(",");
	    List<String> serverNameList = Arrays.asList(allowdServerName);
	    for(String str : serverNameList){
	      if(!isEmpty(str) && str.equals(serverName)){
	        return true;
	      }
	    }
	    return false;
	  }
	 
	  /**
	   * 判空
	   */
	  public boolean isEmpty(Object str) {
	    return str == null || "".equals(str);
	  }
	
 
}